package com.lzy.cloud.payment.utils;

import com.lzy.cloud.payment.pay.alipay.AlipayConfig;
import com.lzy.cloud.payment.pay.weixin.Config;
import org.json.JSONObject;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @ClassName:  Common
 * @Description:TODO   支付基础公共类
 * @author: stone
 * @date:   2017年5月9日 上午9:33:03
 *
 * @Copyright: 2017 www.tydic.com Inc. All rights reserved.
 *
 */
public class Common {


	 /**
	  * 将实体对象转化成Map
	  * @param bean
	  * @return
	  * @throws IntrospectionException
	  * @throws IllegalAccessException
	  * @throws InvocationTargetException
	  */
	 @SuppressWarnings({ "rawtypes", "unchecked" })
	 public static Map convertBean(Object bean)
		        throws IntrospectionException, IllegalAccessException, InvocationTargetException {
		    Class type = bean.getClass();
		    Map returnMap = new HashMap();
		    BeanInfo beanInfo = Introspector.getBeanInfo(type);

		    PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
		    for (int i = 0; i< propertyDescriptors.length; i++) {
		        PropertyDescriptor descriptor = propertyDescriptors[i];
		        String propertyName = descriptor.getName();
		        if (!propertyName.equals("class")) {
		            Method readMethod = descriptor.getReadMethod();
		            Object result = readMethod.invoke(bean, new Object[0]);
		            if (result != null) {
		                returnMap.put(propertyName, result);
		            } else {
		                returnMap.put(propertyName, "");
		            }
		        }
		    }
		    return returnMap;
		}
	/**
	 * 将字符串转化为Map
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	 @SuppressWarnings("unchecked")
	public static Map<String,String> jsonToObject(String jsonStr) throws Exception {
		JSONObject jsonObj = new JSONObject(jsonStr);
		Iterator<String> nameItr = jsonObj.keys();
		String name;
		Map<String, String> outMap = new HashMap<String, String>();
		while (nameItr.hasNext()) {
		name = nameItr.next();
		outMap.put(name, jsonObj.getString(name));
		}
		return outMap;
	}
	 /**
	 * 字符串转换成日期
	 * @param str
	 * @return date
	 */
	 public static Date StrToDate(String str) {
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Date date = null;
	    try {
	     date = format.parse(str);
	    } catch (ParseException e) {
	     e.printStackTrace();
	    }
	    return date;
	 }
	 /**
	 * 日期转换成字符串
	 * @param date
	 * @return str
	 */
	 public static String DateToStr(Date date) {
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    String str = format.format(date);
	    return str;
	 }

	 /**
	  * 获取时间
	  * @param date  当前时间
	  * @param formatDate  yyyy-MM-dd、 yyyy-MM-dd HH:mm:ss
	  * @return
	  */
	 public static String getTime(Date date ,String formatDate) {
	    SimpleDateFormat format = new SimpleDateFormat(formatDate);
	    String str = format.format(date);
	    return str;
	 }
	 /**
	  * 验证手机号码是否正确
	  * @param mobile
	  * @return
	  */
	 public static boolean  validateMobile(String mobile){
		Pattern p = Pattern.compile("^((15[0-9])|(18[0-9])|(17[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobile);
        if (!m.matches()) {
            return false;
        }
        return true;
	 }
	 /**
	  * 金额格式化--微信专用
	  * @param amount
	  * @return
	  */
	 public static String formatString(String amount){
		 double number = Double.parseDouble(amount) * 100;
		 int num = (int) number;
		 return String.valueOf(num);
	 }
	 /**
	  * 昨日日期
	  * @return
	  */
	 public static String getYesTime(){
		Format f = new SimpleDateFormat("yyyy-MM-dd");
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        c.add(Calendar.DAY_OF_MONTH, -1);// 昨天

        Date yesterday = c.getTime();
        return f.format(yesterday);
	 }

	 /**
	  * 获取配置信息值
	  * @param fileName  文件名称
	  * @param key   键
	  * @return  value  值
	  */
	 public static String getValue(String fileName,String key){
		InputStream in=Common.class.getClassLoader().getResourceAsStream(fileName);
		Properties pro=new Properties();
		String value=null;
		try {
			pro.load(in);
			value=pro.getProperty(key);
			return value;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return value;
	 }

	 /**
	  * 获取支付宝配置参数
	  * @param key
	  * @return
	  */
	 public static String getAlipayValue(String key){
		 return getValue("props/alipay.properties",key);
	 }
	 /**
	  * 获取微信配置参数
	  * @param key
	  * @return
	  */
	 public static String getWeixinValue(String key){
		 return getValue("props/weixin.properties",key);
	 }

	/**
	 * 交易手续费
	 * param way  支付方式
	 * param amount 交易金额
	 * @return
	*/
	public static BigDecimal getTradeFee(int type,String amount){
		BigDecimal standard = new BigDecimal("0.005");  //标准收费分界线  5里   0.005元   支付宝和微信通用
		switch (type){
			case 0:
				//获取手续费费率
				BigDecimal alipayRate = BigDecimal.valueOf(Double.parseDouble(AlipayConfig.FEE));
				BigDecimal alipayTradeAmount = BigDecimal.valueOf(Double.parseDouble(amount));
				BigDecimal alipayFee = alipayRate.multiply(alipayTradeAmount);
				//计算手续费
				if(alipayFee.compareTo(standard) < 0){
					return BigDecimal.valueOf(0d);
				}else{
					  DecimalFormat df2 =new DecimalFormat("0.00");
					  String tradeFee =df2.format(alipayFee);
					  return new BigDecimal(tradeFee);
				}
			case 1:
				//获取手续费费率
				BigDecimal weixinRate = BigDecimal.valueOf(Double.parseDouble(Config.FEE));
				BigDecimal weixinTradeAmount = BigDecimal.valueOf(Double.parseDouble(amount)).divide(new BigDecimal(100));
				BigDecimal weixinfee = weixinRate.multiply(weixinTradeAmount);
				if(weixinfee.compareTo(standard) < 0){
					return BigDecimal.valueOf(0d);
				}else{
					DecimalFormat df2 =new DecimalFormat("0.00");
					String tradeFee =df2.format(weixinfee);
					return new BigDecimal(tradeFee);
				}
		}
		return null;
	}
	/**
	 * 退款手续费--微信
	 * @param refundAmount 实际退款金额
	 * @return
	 */
	public static BigDecimal getRefundFee(BigDecimal refundAmount){
		//获取手续费费率
		BigDecimal weixinRate = BigDecimal.valueOf(Double.parseDouble(Config.FEE));
		BigDecimal weixinRefundFee = weixinRate.multiply(refundAmount);
		BigDecimal standard = new BigDecimal("0.005");  //标准收费分界线  5里   0.005元   支付宝和微信通用
		//计算出结果
		if(weixinRefundFee.compareTo(standard) < 0){
			return BigDecimal.valueOf(0d);
		}else{
			DecimalFormat df2 =new DecimalFormat("0.00");
			String tradeFee =df2.format(weixinRefundFee);
			return new BigDecimal(tradeFee);
		}
	}
	public static void main(String[] args) {
		/*System.out.println(getTradeFee(1,"1"));*/
		System.out.println(getRefundFee(new BigDecimal(10)));
		/*BigDecimal b = new BigDecimal(1);
		System.out.println(b.divide(new BigDecimal(100)));*/

	}
}
